#ifndef     __SYNC_VALUE_H
#define     __SYNC_VALUE_H

#include "./cond_var.h"

namespace rtos {

template <typename T>
class SyncValue {

public:
    void set(const T &value) {
        m_cond.lock();
        m_value = value;
        m_update_flag = true;
        m_cond.notify();
        m_cond.unlock();
    }

    bool get(T &value, uint32_t timeout = osWaitForever) {
        do {
            m_cond.lock();
            if (!m_update_flag) {
                m_cond.unlock();
                if (!m_cond.wait(timeout)) {
                    return false;
                }
                continue;
            }
        } while (false);
        value = m_value;
        m_update_flag = false;
        m_cond.unlock();
        return true;
    }

private:
    T m_value;
    bool m_update_flag = false;
    CondVar m_cond;
};

}


#endif
